/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package commonlib.persistance;

import commonlib.domain.ABPair;
import commonlib.domain.Corpus;
import java.io.*;
import java.util.*;

/**
 *This class manages reads and writes from and to the corpusFile file.
 * @author marc.mauri
 */
public abstract class CorpusDataManager {

    /**
     * This is the file where corpusFile is stored.
     */
    protected File corpusFile;

    public void writeCorpus(Corpus corpus) throws IOException {
        corpusFile.delete();

        corpusFile.createNewFile();

        Iterator it = corpus.iterator();

        FileWriter flw = new FileWriter(corpusFile);
        BufferedWriter bw = new BufferedWriter(flw);

        while (it.hasNext() ) {
            ABPair pair = (ABPair)it.next();
            String line = this.writeLine(pair);

            bw.write(line);
            bw.newLine();
        }

        bw.close();
    }

    public Corpus readCorpus() throws FileNotFoundException, IOException {
        Scanner sc = new Scanner(corpusFile);
        Corpus corpus = new Corpus();
        while (sc.hasNextLine() ) {
            ABPair[] parells = readLine(sc.nextLine() );
            for (int i = 0; i < parells.length; ++i) {
                corpus.AddPair(parells[i].getAlpha(), parells[i].getBeta());
            }
        }
        sc.close();
        return corpus;
    }

    abstract protected String writeLine(ABPair pair) throws IOException;

    abstract protected ABPair[] readLine(String line) throws IOException;

}